<template>
  <div ref="content">
    <a-card :bordered="false">
      <!-- 增加 -->
      <biz-product-add-form
        v-if="showAddModal"
        ref="bizProductAddForm"
        :categoryIdOptions="categoryIdOptions"
        :warehouseList="warehouseList"
        :inventoryOptions="inventoryOptions"
        @ok="getList"
        @select-tree="getTreeSelect"
        @select="getWarehouseList"
        @close="showAddModal = false"
      />
      <biz-product-edit-form
        v-if="showEditModal"
        ref="bizProductEditForm"
        :categoryIdOptions="categoryIdOptions"
        :warehouseList="warehouseList"
        :inventoryOptions="inventoryOptions"
        @ok="getList"
        @select="getWarehouseList"
        @select-tree="getTreeSelect"
        @close="showEditModal = false"
      />
      <!--设置工序-->
      <biz-product-set-process
        v-if="showProcessModal"
        ref="bizProductSetProcess"
        @ok="getList"
        @close="showProcessModal = false"
      />
      <a-page-header
        style="border-bottom: 1px solid rgb(235, 237, 240);padding:8px 16px;"
        title=""/>
      <split splitHeight="100%" leftWidth="220" >
        <template slot="paneL">
          <!-- 部门树 -->
          <category-tree
            ref="deptTree"
            :categoryOptions="categoryOptions"
            :defalutExpandedKeys="expandedKeys"
            @setDataOptionInfo="setDataOptionInfo"
            @select="clickCategoryNode"
          />
        </template>
        <template slot="paneR">
          <!-- 条件搜索 -->
          <div class="table-page-search-wrapper">
            <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
              <a-row :gutter="32">
<!--                <a-col :span="6" >
                  <a-form-item label="产品大类">
                    <a-input v-model="queryParam.categoryName" placeholder="请输入产品大类" allow-clear @keyup.enter.native="handleQuery"/>
                  </a-form-item>
                </a-col>-->
                <a-col :span="6" >
                  <a-form-item label="查询条件">
                    <a-input v-model="queryParam.orderParams" placeholder="请输入查询条件" allow-clear @keyup.enter.native="handleQuery"/>
                  </a-form-item>
                </a-col>
<!--                <a-col :span="6" >-->
<!--                  <a-form-item label="助记码">-->
<!--                    <a-input v-model="queryParam.mnemonicCode" placeholder="请输入助记码" allow-clear @keyup.enter.native="handleQuery"/>-->
<!--                  </a-form-item>-->
<!--                </a-col>-->
                <a-col>
              <span class="table-page-search-submitButtons" style="float: right;">
                <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
              </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <a-divider />
          <advance-table
          :components="drag(columns)"
            title="产品管理"
            :pagination="{
          current: queryParam.pageNum,
          pageSize: queryParam.pageSize,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: changeSize,
          onShowSizeChange: onShowSizeChange
        }"
            tableKey="base-bizProduct-index-table"
            @change="handleTableChange"
            rowKey="id"
            size="middle"
            @refresh="getList"
            :columns="columns"
            :data-source="bizProductList"
            :loading="loading"
            :format-conditions="true"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          >
            <div class="table-operations" slot="button">
              <a-button type="primary" @click="handleAdd" v-hasPermi="['biz:bizProduct:add']">
                <a-icon type="plus" />新增
              </a-button>
              <a-button type="danger" v-if="!multiple" :disabled="multiple" @click="handleDelete" v-hasPermi="['biz:bizProduct:remove']">
                <a-icon type="delete" />删除
              </a-button>
              <a-button type="" @click="handleExport" v-hasPermi="['biz:bizProduct:export']">
                <a-icon type="download" />导出
              </a-button>
            </div>
            <span slot="defaultOption" slot-scope="{record}">
          {{ defaultOptionFormat(record) }}
        </span>
            <span slot="inventoryFlagSlot" slot-scope="{record}">
              <a-tag color="green" v-if="record.inventoryFlag === '1'">
                是
              </a-tag>
              <a-tag color="red" v-else-if="record.inventoryFlag === '0'">
                否
              </a-tag>
              <a-tag color="orange" v-else>
                未设置
              </a-tag>
            </span>
            <span slot="warehouseId" slot-scope="{record}">
          {{ warehouseIdFormat(record) }}
        </span>
            <span slot="operation" slot-scope="{text, record}">
          <a @click="handleUpdate(record)" v-hasPermi="['biz:bizProduct:edit']">
            修改
          </a>
            <a-divider type="vertical" v-hasPermi="['biz:bizProduct:remove']"/>
                <a @click="handleSetProcess(record)" v-hasPermi="['biz:bizProduct:edit']">
            工序计划
          </a>
          <a-divider type="vertical" v-hasPermi="['biz:bizProduct:remove']"/>
          <a @click="handleDelete(record)" v-hasPermi="['biz:bizProduct:remove']">
            删除
          </a>
        </span>
          </advance-table>
        </template>
      </split>
    </a-card>
  </div>
</template>

<script>
import { listBizProduct, delBizProduct, exportBizProduct, getInitData } from '@/api/biz/bizProduct'
import { listTree, listTreeExcludeChild } from '@/api/biz/bizProductCategory'
import { allListBizWarehouse } from '@/api/biz/bizWarehouse'
import CategoryTree from './modules/CategoryTree'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import Split from '@/components/pt/split/Index'
import BizProductAddForm from '@/views/biz/bizproduct/modules/BizProductAddForm'
import BizProductEditForm from '@/views/biz/bizproduct/modules/BizProductEditForm'
import BizProductSetProcess from '@/views/biz/bizproduct/modules/BizProductSetProcess'
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
export default {
  name: 'User',
  components: {
    AdvanceTable,
    BizProductAddForm,
    BizProductEditForm,
    Split,
    CategoryTree,
    BizProductSetProcess
  },
  mixins:[tableDragResizeMixin],
  data () {
    return {
      showAddModal: false,
      showEditModal: false,
      showProcessModal:false,
      list: [],
      tableTitle: '产品管理',
      selectedRowKeys: [],
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      expandedKeys: [],
      loading: false,
      total: 0,
      categoryCheckedValue: {},
      // 所属分类字典
      categoryIdOptions: [],
      warehouseList: [],
      bizProductList:[],
      // 产品分类树选项
      categoryOptions: [],

      // 库存计算字典
      inventoryOptions:[],
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        categoryId: undefined,
        orderParams: undefined,

        productCode: undefined,

        mnemonicCode: undefined

      },
      columns: [
        {
          title: '产品大类',
          dataIndex: 'categoryName',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '产品编号',
          dataIndex: 'productCode',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '助记码',
          dataIndex: 'mnemonicCode',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '默认仓库',
          dataIndex: 'warehouseName',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '规格',
          dataIndex: 'spec',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '预警库存',
          dataIndex: 'warnStock',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '工序计划',
          dataIndex: 'planName',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '库存计算',
          dataIndex: 'inventoryFlag',
          ellipsis: true,
          align: 'left',
          width: '12.8%',
          scopedSlots: { customRender: 'inventoryFlagSlot' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  filters: {
  },
  created () {
    this.getList()
    this.getTreeselect()
    getInitData('inventory_flag').then(response => {
      this.inventoryOptions = response.data.inventory_flag
    })
  },
  computed: {
  },
  watch: {
  },
  methods: {
    importTemplate (expanded, record) {
      importTemplate().then(response => {
        this.download(response.msg)
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect () {
       listTree('0', 3).then(response => {
        this.categoryOptions = response.data
        this.getExpandedKeys(this.categoryOptions, 3)
      })
    },
    getExpandedKeys (nodes, expandLevel) {
      if (expandLevel > 1) {
        // 最后一层不展开
        if(!nodes) {
          return;
        }
        nodes.forEach(node => {
        this.expandedKeys.push(node.id)
        expandLevel = expandLevel - 1
        return this.getExpandedKeys(node.children, expandLevel)
        })
      }
    },
    /** 查询定时任务列表 */
    getList () {
      this.loading = true
      listBizProduct(this.queryParam).then(response => {
        this.bizProductList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        categoryId: undefined,

        productCode: undefined,

        mnemonicCode: undefined

      }
      this.handleQuery()
    },
    onShowSizeChange (current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    changeSize (current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    clickCategoryNode (node) {
      this.queryParam.categoryId = node.$options.propsData.eventKey
      this.categoryCheckedValue.ids = node.$options.propsData.eventKey
      this.tableTitle = node.$options.propsData.label
      if (node.$options.propsData.dataRef.attributes.deptType === 'dept') {
        this.categoryCheckedValue = { ids: node.$options.propsData.eventKey, names: node.$options.propsData.label }
      } else {
        this.categoryCheckedValue = {}
      }
      this.getList()
    },
    handleAdd () {
      this.showAddModal = true
      this.$nextTick(() => (
        this.$refs.bizProductAddForm.handleAdd()
      ))
    },
    handleUpdate (record, ids) {
      this.showEditModal = true
      this.$nextTick(() => (
        this.$refs.bizProductEditForm.handleUpdate(record, ids)
      ))
    },
    handleSetProcess (record, ids) {
      this.showProcessModal = true
      this.$nextTick(() => {
        this.$refs.bizProductSetProcess.handleSetProcess(record, ids);
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      var that = this
      const bizProductIds = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk () {
          return delBizProduct(bizProductIds)
            .then(() => {
              that.onSelectChange([], [])
              that.getList()
              that.$message.success(
                '删除成功',
                3
              )
            })
        },
        onCancel () {}
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      var that = this
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk () {
          return exportBizProduct(that.queryParam)
            .then(response => {
              that.download(response.msg)
              that.$message.success(
                '导出成功',
                3
              )
            })
        },
        onCancel () {}
      })
    },
    setDataOptionInfo (treeDataOption) {
       this.categoryOptions = treeDataOption
    },
    handleTableChange (pagination, filters, sorter) {
      if (sorter.field !== undefined && sorter.field !== null && sorter.field !== '') {
        this.queryParam.orderByColumn = 't.' + sorter.field
        this.queryParam.isAsc = sorter.order
      }
      this.getList()
    },
    /** 查询菜单下拉树结构 */
    getTreeSelect (row) {
      if (row) {
        listTreeExcludeChild(row.id, '99').then(response => {
          this.categoryIdOptions=response.data;
        })
      } else {
        listTree('0', '99').then(response => {
          this.categoryIdOptions=response.data;
        })
      }
    },
    getWarehouseList() {
      allListBizWarehouse().then(response => {
        this.warehouseList = response.data
      })
    },
    // 所属仓库字典翻译
    warehouseIdFormat (row) {
      if (row.warehouseId) {
        return this.selectDictLabel(this.warehouseList, row.warehouseId)
      } else {
        return ''
      }
    },
    selectDictLabel (datas, value) {
      var actions = []
      Object.keys(datas).some((key) => {
        if (datas[key].id === ('' + value)) {
          actions.push(datas[key].warehouseName)
          return true
        }
      })
      return actions.join('')
    },
    
  }
}
</script>
<style lang="less" scoped>
  .ant-divider-horizontal {
      margin:  0;
      background: rgb(235, 237, 240);
  }
  .demo-split{
      height: 200px;
  }
  .demo-split-pane{
      padding: 10px;
  }
  .ant-avatar{
        font-size: 12px;
        border-radius: 4px;
        vertical-align: middle;
        margin-right: 8px;
  }
</style>
